<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>访问说明符</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/access","wgTitle":"cpp/language/access","wgCurRevisionId":64721,"wgArticleId":2677,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/access","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_access skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">访问说明符</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="classes.html" title="cpp/language/classes">类</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv-h2"><td colspan="5">概述</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="classes.html" title="cpp/language/classes">综述</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="class.html" title="cpp/language/class"><code>class</code>/<code>struct</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="union.html" title="cpp/language/union"><code>union</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="injected-class-name.html" title="cpp/language/injected-class-name">注入类名</a> </td></tr>
<tr class="t-nv-h2"><td colspan="5">成员</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html" title="cpp/language/data members">数据成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="static.html" title="cpp/language/static">静态成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="this.html" title="cpp/language/this"><code>this</code> 指针</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="nested_classes.html" title="cpp/language/nested types">嵌套类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_template.html" title="cpp/language/member template">成员模板</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="bit_field.html" title="cpp/language/bit field">位域</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="using_declaration.html" title="cpp/language/using declaration"><code>using</code> 声明</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_functions.html" title="cpp/language/member functions">成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink">成员访问指定符</strong></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="constructor.html" title="cpp/language/initializer list">构造函数与成员初始化器列表</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="friend.html" title="cpp/language/friend"><code>friend</code> 指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="explicit.html" title="cpp/language/explicit"><code>explicit</code> 指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="converting_constructor.html" title="cpp/language/converting constructor">转换构造函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">特殊成员函数</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="default_constructor.html" title="cpp/language/default constructor">默认构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_constructor.html" title="cpp/language/copy constructor">复制构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_constructor.html" title="cpp/language/move constructor">移动构造函数</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_assignment.html" title="cpp/language/copy assignment">复制赋值运算符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_assignment.html" title="cpp/language/move assignment">移动赋值运算符</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="destructor.html" title="cpp/language/destructor">析构函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">继承</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="derived_class.html" title="cpp/language/derived class">基与派生类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="ebo.html" title="cpp/language/ebo">空基类优化</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="virtual.html" title="cpp/language/virtual">虚成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="abstract_class.html" title="cpp/language/abstract class">纯虚函数与抽象类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="override.html" title="cpp/language/override"><tt>override</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="final.html" title="cpp/language/final"><tt>final</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>在 <a href="class.html" title="cpp/language/class">class/struct</a> 或 <a href="union.html" title="cpp/language/union">union</a> 的 <span class="t-spar">成员说明</span> 中，定义其后继成员的可访问性。
</p><p>在<a href="derived_class.html" title="cpp/language/derived class">派生类</a>声明的 <span class="t-spar">基类说明符</span> 中，定义继承自其后继的基类的成员的可访问性。
</p>
<h3><span class="mw-headline" id=".E8.AF.AD.E6.B3.95">语法</span></h3>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>public</b></code>  <code><b>:</b></code> <span class="t-spar">成员说明</span>
</td>
<td> (1)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>protected</b></code> <code><b>:</b></code> <span class="t-spar">成员说明</span>
</td>
<td> (2)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>private</b></code> <code><b>:</b></code> <span class="t-spar">成员说明</span>
</td>
<td> (3)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">public</span></span></span> <span class="t-spar">基类</span>
</td>
<td> (4)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">protected</span></span></span> <span class="t-spar">基类</span>
</td>
<td> (5)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">private</span></span></span> <span class="t-spar">基类</span>
</td>
<td> (6)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<div class="t-li1"><span class="t-li">1)</span> 该访问说明符之后的各个成员具有公开成员访问</div>
<div class="t-li1"><span class="t-li">2)</span> 该访问说明符之后的各个成员具有受保护成员访问</div>
<div class="t-li1"><span class="t-li">3)</span> 该访问说明符之后的各个成员具有私有成员访问</div>
<div class="t-li1"><span class="t-li">4)</span> <a href="derived_class.html#.E5.85.AC.E5.BC.80.E7.BB.A7.E6.89.BF" title="cpp/language/derived class">公开继承</a>：该访问说明符之后列出的<a href="derived_class.html" title="cpp/language/derived class">基类</a>的公开和受保护成员在派生类中保持其成员访问，而基类的私有成员对派生类不可访问</div>
<div class="t-li1"><span class="t-li">5)</span> <a href="derived_class.html#.E5.8F.97.E4.BF.9D.E6.8A.A4.E7.BB.A7.E6.89.BF" title="cpp/language/derived class">受保护继承</a>：该访问说明符之后列出的<a href="derived_class.html" title="cpp/language/derived class">基类</a>的公开和受保护成员在派生类中是受保护成员，而基类的私有成员对派生类不可访问</div>
<div class="t-li1"><span class="t-li">6)</span> <a href="derived_class.html#.E7.A7.81.E6.9C.89.E7.BB.A7.E6.89.BF" title="cpp/language/derived class">私有继承</a>：该访问说明符之后列出的<a href="derived_class.html" title="cpp/language/derived class">基类</a>的公开和受保护成员在派生类中是私有成员，而基类的私有成员对派生类不可访问</div>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<p>每个<a href="class.html" title="cpp/language/class">类</a>成员（静态、非静态、函数、类型等）的名字都具有与其关联的“成员访问”。在程序的任何位置使用成员的名字时，检查其访问，而且若它不满足访问规则，则程序不能编译：
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="kw1">class</span> Example <span class="br0">{</span>
 <span class="kw1">public</span><span class="sy4">:</span>              <span class="co1">// 此点后的所有声明为公开</span>
    <span class="kw4">void</span> add<span class="br0">(</span><span class="kw4">int</span> x<span class="br0">)</span> <span class="br0">{</span> <span class="co1">// 成员 "add" 具有公开访问</span>
        n <span class="sy2">+</span><span class="sy1">=</span> x<span class="sy4">;</span>       <span class="co1">// OK：从 Example::add 可以访问受保护的 Example::n</span>
    <span class="br0">}</span>
 <span class="kw1">private</span><span class="sy4">:</span>             <span class="co1">// 此点后的所有声明为私有</span>
    <span class="kw4">int</span> n <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span>        <span class="co1">// 成员 "n" 具有私有访问</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    Example e<span class="sy4">;</span>
    e.<span class="me1">add</span><span class="br0">(</span><span class="nu0">1</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// OK：从 main 可以访问公开的 Example::add</span>
<span class="co1">//  e.n = 7;  // 错误：从 main 不能访问私有的 Example::n</span>
<span class="br0">}</span></pre></div></div>
<p><br> 
</p>
</div>
<p>访问说明符给予类作者决定哪些类成员能被类的用户所访问（即类的<i>接口</i>），而哪些成员用于内部使用（即其<i>实现</i>）的能力。
</p>
<h3><span class="mw-headline" id=".E7.BB.86.E8.8A.82">细节</span></h3>
<p>类的所有成员（<a href="member_functions.html" title="cpp/language/member functions">成员函数</a>体，成员对象的初始化器，以及整个<a href="nested_classes.html" title="cpp/language/nested types">嵌套类定义</a>），都拥有对类所能访问的所有名字的访问权。成员函数内的局部类拥有对成员函数所能访问的所有名字的访问权。
</p><p>以关键词 <code>class</code> 定义的类，其成员和其基类默认具有私有访问。以关键词 <code>struct</code> 定义的类，其成员和其基类默认具有公开访问。<a href="union.html" title="cpp/language/union">union</a> 的成员默认具有公开访问。
</p><p>若要向其他函数或类授予对受保护或私有成员的访问权，可使用<a href="friend.html" title="cpp/language/friend">友元声明</a>。
</p><p>可访问性应用到所有名字，而不考虑其来源，因此受检查的是以 <a href="typedef.html" title="cpp/language/typedef">typedef</a> 或 <a href="using_declaration.html" title="cpp/language/using declaration">using 声明</a>引入的名字，而非其所指涉的名字：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> A <span class="sy4">:</span> X <span class="br0">{</span>
  <span class="kw1">class</span> B <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span>  <span class="co1">// B 在 A 中为私有</span>
<span class="kw1">public</span><span class="sy4">:</span>
  <span class="kw1">typedef</span> B BB<span class="sy4">;</span> <span class="co1">// BB 为公开</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
  A<span class="sy4">::</span><span class="me2">B</span> y<span class="sy4">;</span>  <span class="co1">// 错误：A::B 为私有</span>
  A<span class="sy4">::</span><span class="me2">BB</span> x<span class="sy4">;</span> <span class="co1">// OK：A::BB 为公开</span>
<span class="br0">}</span></pre></div></div>
<p>成员访问不影响可见性：私有和私有继承的成员对重载决议可见并被其考虑，到不可访问基类的隐式转换也仍被考虑，等等。成员访问检查是对任何给定语言构造进行解释之后的最后一步。此规则的目的是使得以 <code>public</code> 替换任何 <code>private</code> 时始终不会改变程序的行为。
</p><p>对于<a href="default_arguments.html" title="cpp/language/default arguments">默认函数实参</a>中以及默认<a href="template_parameters.html#.E9.BB.98.E8.AE.A4.E6.A8.A1.E6.9D.BF.E5.AE.9E.E5.8F.82" title="cpp/language/template parameters">模板形参</a>中所使用的名字的访问检查，在声明点而非在使用点进行。
</p><p>对<a href="virtual.html" title="cpp/language/virtual">虚函数</a>的名字的访问规则，在调用点，使用（用于代表调用该成员函数的对象的）表达式的类型进行检查。忽略最终覆盖函数的访问：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> B <span class="br0">{</span> <span class="kw1">virtual</span> <span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span> <span class="co1">// f 在 B 中为公开</span>
<span class="kw1">class</span> D <span class="sy4">:</span> <span class="kw1">public</span> B <span class="br0">{</span> <span class="kw1">private</span><span class="sy4">:</span> <span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span> <span class="co1">// f 在 D 中为私有</span>
<span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
 D d<span class="sy4">;</span>
 B<span class="sy3">&amp;</span> b <span class="sy1">=</span> d<span class="sy4">;</span>
 b.<span class="me1">f</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// OK：B::f() 为公开，调用 D::f()，即使它为私有</span>
 d.<span class="me1">f</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 错误：D::f() 为私有</span>
<span class="br0">}</span></pre></div></div>
<p>根据无限定<a href="lookup.html" title="cpp/language/lookup">名字查找</a>为私有的名字，有可能通过有限定名字查找访问：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> A <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> B <span class="sy4">:</span> <span class="kw1">private</span> A <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> C <span class="sy4">:</span> <span class="kw1">public</span> B <span class="br0">{</span>
   A<span class="sy2">*</span> p<span class="sy4">;</span>   <span class="co1">// 错误：无限定名字查找找到作为 B 的私有基类的 A</span>
   <span class="sy4">::</span><span class="me2">A</span><span class="sy2">*</span> q<span class="sy4">;</span> <span class="co1">// OK：有限定名字查找找到命名空间层级的声明</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>可通过继承图中多条路径访问的名字，具有带最大访问的路径上的访问：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> W <span class="br0">{</span> <span class="kw1">public</span><span class="sy4">:</span> <span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> A <span class="sy4">:</span> <span class="kw1">private</span> <span class="kw1">virtual</span> W <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> B <span class="sy4">:</span> <span class="kw1">public</span> <span class="kw1">virtual</span> W <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> C <span class="sy4">:</span> <span class="kw1">public</span> A, <span class="kw1">public</span> B <span class="br0">{</span>
<span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> W<span class="sy4">::</span><span class="me2">f</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span> <span class="co1">// OK：W 通过 B 对 C 是可访问的</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>类中可以任何顺序出现任何数量的访问说明符。成员访问说明符可能影响类的布局：非静态<a href="data_members.html#.E5.B8.83.E5.B1.80" title="cpp/language/data members">数据成员</a>的地址只保证对于具有相同访问的成员以声明顺序增加。对于<a href="../named_req/StandardLayoutType.html" title="cpp/named req/StandardLayoutType"><i>标准布局类型</i> <span style="font-family: Georgia, 'DejaVu Serif', serif; font-style:italic">(StandardLayoutType)</span> </a>，所有非静态数据成员必须具有相同访问。
</p><p>在类中重声明成员时，必须在相同成员访问下进行：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> S <span class="br0">{</span>
  <span class="kw1">class</span> A<span class="sy4">;</span>    <span class="co1">// S::A 公开</span>
<span class="kw1">private</span><span class="sy4">:</span>
  <span class="kw1">class</span> A <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 错误：不能更改访问</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<h3><span class="mw-headline" id=".E5.85.AC.E5.BC.80.E6.88.90.E5.91.98.E8.AE.BF.E9.97.AE">公开成员访问</span></h3>
<p>公开成员组成类公开接口的一部分（公开接口的其他部分是由 <a href="adl.html" title="cpp/language/adl">ADL</a> 所找到的非成员函数）。
</p><p>类的公开成员可在任何位置访问。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> S <span class="br0">{</span>
 <span class="kw1">public</span><span class="sy4">:</span> <span class="co1">// n、E、A、B、C、U、f 是公开成员</span>
    <span class="kw4">int</span> n<span class="sy4">;</span>
    <span class="kw2">enum</span> E <span class="br0">{</span>A, B, C<span class="br0">}</span><span class="sy4">;</span>
    <span class="kw1">struct</span> U <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
    <span class="kw4">static</span> <span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    S<span class="sy4">::</span><span class="me2">f</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>     <span class="co1">// S::f 于 main 可访问</span>
    S s<span class="sy4">;</span>
    s.<span class="me1">n</span> <span class="sy1">=</span> S<span class="sy4">::</span><span class="me2">B</span><span class="sy4">;</span> <span class="co1">// S::n 与 S::B 于 main 可访问</span>
    S<span class="sy4">::</span><span class="me2">U</span> x<span class="sy4">;</span>     <span class="co1">// S::U 于 main 可访问</span>
<span class="br0">}</span></pre></div></div>
<h3><span class="mw-headline" id=".E5.8F.97.E4.BF.9D.E6.8A.A4.E6.88.90.E5.91.98.E8.AE.BF.E9.97.AE">受保护成员访问</span></h3>
<p>受保护成员访问组成针对类对其派生类的接口（与类的公开接口有别）。
</p><p>类的受保护成员只能为下列者所访问
</p>
<div class="t-li1"><span class="t-li">1)</span> 该类的成员和友元</div>
<div class="t-li1"><span class="t-li">2)</span> 派生自该类的任何类的成员<span class="t-rev-inl t-until-cxx17"><span>和友元</span> <span><span class="t-mark-rev t-until-cxx17">(C++17 前)</span></span></span>，但仅在访问受保护成员所通过的对象的类是该派生类或该派生类的派生类时允许：</div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> Base <span class="br0">{</span>
 <span class="kw1">protected</span><span class="sy4">:</span>
    <span class="kw4">int</span> i<span class="sy4">;</span>
 <span class="kw1">private</span><span class="sy4">:</span>
    <span class="kw4">void</span> g<span class="br0">(</span>Base<span class="sy3">&amp;</span> b, <span class="kw1">struct</span> Derived<span class="sy3">&amp;</span> d<span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw1">struct</span> Derived <span class="sy4">:</span> Base <span class="br0">{</span>
    <span class="kw4">void</span> f<span class="br0">(</span>Base<span class="sy3">&amp;</span> b, Derived<span class="sy3">&amp;</span> d<span class="br0">)</span> <span class="co1">// 派生类的成员函数</span>
    <span class="br0">{</span>
        <span class="sy2">++</span>d.<span class="me1">i</span><span class="sy4">;</span>                  <span class="co1">// OK：d 的类型是 Derived</span>
        <span class="sy2">++</span>i<span class="sy4">;</span>                    <span class="co1">// OK：隐含的 '*this' 的类型为 Derived</span>
<span class="co1">//      ++b.i;                  // 错误：不能通过 Base 访问受保护成员</span>
                                <span class="co1">// （否则可能更改另一派生类，假设为 Derived2 的基实现）</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">void</span> Base<span class="sy4">::</span><span class="me2">g</span><span class="br0">(</span>Base<span class="sy3">&amp;</span> b, Derived<span class="sy3">&amp;</span> d<span class="br0">)</span> <span class="co1">// Base 的成员函数</span>
<span class="br0">{</span>
    <span class="sy2">++</span>i<span class="sy4">;</span>                          <span class="co1">// OK</span>
    <span class="sy2">++</span>b.<span class="me1">i</span><span class="sy4">;</span>                        <span class="co1">// OK</span>
    <span class="sy2">++</span>d.<span class="me1">i</span><span class="sy4">;</span>                        <span class="co1">// OK</span>
<span class="br0">}</span>
 
<span class="kw4">void</span> x<span class="br0">(</span>Base<span class="sy3">&amp;</span> b, Derived<span class="sy3">&amp;</span> d<span class="br0">)</span> <span class="co1">// 非成员非友元</span>
<span class="br0">{</span>
<span class="co1">//    ++b.i;                // 错误：非成员不能访问</span>
<span class="co1">//    ++d.i;                // 错误：非成员不能访问</span>
<span class="br0">}</span></pre></div></div>
<p>组成指向受保护成员的指针时，必须在其声明中使用派生类：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> Base <span class="br0">{</span>
 <span class="kw1">protected</span><span class="sy4">:</span>
    <span class="kw4">int</span> i<span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw1">struct</span> Derived <span class="sy4">:</span> Base <span class="br0">{</span>
    <span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span>
    <span class="br0">{</span>
<span class="co1">//      int Base::* ptr = &amp;Base::i;    // 错误：必须使用 Derived 来指名</span>
        <span class="kw4">int</span> Base<span class="sy4">::</span><span class="sy2">*</span> ptr <span class="sy1">=</span> <span class="sy3">&amp;</span>Derived<span class="sy4">::</span><span class="me2">i</span><span class="sy4">;</span> <span class="co1">// OK</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<h3><span class="mw-headline" id=".E7.A7.81.E6.9C.89.E6.88.90.E5.91.98.E8.AE.BF.E9.97.AE">私有成员访问</span></h3>
<p>私有成员组成类的实现，以及针对类的其他成员的私有接口。
</p><p>类的私有成员仅对类的成员和友元可访问，无关乎成员在相同还是不同实例：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> S <span class="br0">{</span>
 <span class="kw1">private</span><span class="sy4">:</span>
    <span class="kw4">int</span> n<span class="sy4">;</span> <span class="co1">// S::n 私有</span>
 <span class="kw1">public</span><span class="sy4">:</span>
    S<span class="br0">(</span><span class="br0">)</span> <span class="sy4">:</span> n<span class="br0">(</span><span class="nu0">10</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>                    <span class="co1">// this-&gt;n 可于 S::S 访问</span>
    S<span class="br0">(</span><span class="kw4">const</span> S<span class="sy3">&amp;</span> other<span class="br0">)</span> <span class="sy4">:</span> n<span class="br0">(</span>other.<span class="me1">n</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="co1">// other.n 可于 S::S 访问</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p><a href="explicit_cast.html" title="cpp/language/explicit cast">显式转型</a>（C 风格与函数风格）允许从派生类左值转型为到其私有基类的引用，或从指向派生类的指针转型为指向其私有基类的指针。
</p>
<h3><span class="mw-headline" id=".E7.BB.A7.E6.89.BF">继承</span></h3>
<p>公开、受保护和私有继承的含义，见<a href="derived_class.html" title="cpp/language/derived class">派生类</a>。
</p>
<!-- 
NewPP limit report
Preprocessor visited node count: 1884/1000000
Preprocessor generated node count: 5456/1000000
Post‐expand include size: 47280/2097152 bytes
Template argument size: 10759/2097152 bytes
Highest expansion depth: 15/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:2677-0!*!0!!zh!*!zh!* and timestamp 20200213085828 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/access&amp;oldid=64721">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/access&amp;oldid=64721</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/access">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2020年2月13日 (星期四) 00:58。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过7,298次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.066 secs. -->
	</body>
<!-- Cached 20200213113811 -->
</html>